js遍历树,多层嵌套for循环,递归

您所在的位置:网站首页 foreach嵌套 有没有好的优化方法 js遍历树,多层嵌套for循环,递归

js遍历树,多层嵌套for循环,递归

2024-07-15 07:04| 来源: 网络整理| 查看: 265

js遍历树,多层嵌套for循环,递归 一、目的源数据示例 二、如何获得数据多层for循环嵌套遍历树数据递归遍历树数据

一、目的

遍历获取树数据中的部分数据。

源数据示例

menuType=2的数据为按钮,按钮可以在一级菜单下也可以在二级菜单下,层级不固定。

// 示例数据 menuType=0为一级菜单,1为按钮,2为二级菜单 let menuTreeList = [ { "id": "cfda8029dfb311e7b555201a068c6482", "name": "系统管理", "menuType": 0, "children": [ { "id": "3873ccc2dfda11e7b555201a068c6483", "name": "菜单管理", "menuType": 2, "children": [ { "id": "18bf8d5df09511e78a57201a068c6484", "name": "新增", "menuType": 1 }, { "id": "18bf8d5df09511e78a57201a068c6485", "name": "修改", "menuType": 1 } ] } ] }, { "id": "cfda8029dfb311e7b555201a068c6486", "name": "设备管理", "menuType": 0, "children": [ { "id": "18bf8d5df09511e78a57201a068c6487", "name": "新增", "menuType": 1 }, { "id": "18bf8d5df09511e78a57201a068c6488", "name": "修改", "menuType": 1 } ] } ] 二、如何获得数据

因为源数据是树形,要用到的也只有menuType=1的数据,所以如果每次判断时都遍历整个树时都会遍历到很多不必要的数据,如menuType=0或者2的数据是不需要的,所以拿到数据的时候就把需要的数据取出来转换成普通数组,这样判断的时候遍历起来更快速与方便。

多层for循环嵌套遍历树数据 for (let item of menuTreeList) { if (item.menuType === 1) { menuList.push({ name: item.name, url: item.url, id: item.id }); } for (let towMenus of item.children) { if (towMenus.menuType === 1) { menuList.push({ name: towMenus.name, url: towMenus.url, id: towMenus.id }); } for (let threeMenus of towMenus.children) { if (threeMenus.menuType === 1) { menuList.push({ name: threeMenus.name, url: threeMenus.url, id: threeMenus.id }); } } } }

上面的源代码只有三级,就已经很长了,而且每多一级就要多想一个变量名,如果层级更多,那光想变量名就头疼了,从可读性与维护性来说都不适合,所以要用递归来实现。

递归遍历树数据

递归,就是在运行的过程中调用自己。用代码来说就是下面第二段代码。

调用方法:

// 菜单按钮权限数据 let menuBtnList = []; // 调用递归方法获得按钮数据 this.getMenuBtnList(resData, menuBtnList); // 保存菜单按钮权限数据至vuex中 this.$store.commit('updateMenuBtnList', {menuBtnList: menuBtnList});

递归方法实现:

getMenuBtnList (menuTreeList, menuList) { for (let item of menuTreeList) { if (item.menuType === 1) { menuList.push({ name: item.name, url: item.url, id: item.id }); } else if (item.children.length > 0 ) { this.getMenuBtnList(item.children, menuList); } } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3